package demoq;

import java.util.Arrays;
import java.util.PriorityQueue;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }
    //创建大根堆
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }//给elem数组传入原始数据
        for (int parent = ((usedSize-1-1)/2); parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }
    private void shiftDown(int parent, int end) {
        int child = parent*2+1;
        //是否存在左孩子
        while (child < end) {
            //是否存在右孩子
            if (child + 1 < end) {
                if (elem[child] < elem[child+1]) {
                    child++;
                }
            }
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = parent*2+1;
            } else {
                break;
            }

        }
    }
    //存储数据
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*usedSize);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while (child > 0) {
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            } else {
                break;
            }
        }
    }
    //删除元素
    public void pop() {
        if(isEmpty()) {
            throw new HeapEmptyException("Heap is empty!");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
    //查看优先级队列首元素
    public int peek() {
        if(isEmpty()) {
            throw new HeapEmptyException("Heap is empty!");
        }
        return elem[0];
    }
    //堆排序
    public void heapSort() {
        int end  = usedSize-1;
        while(end > 0) {
            int tmp = elem[end];
            elem[end] = elem[0];
            elem[0] = tmp;
            shiftDown(0,end);
            end--;
        }
    }
}
